package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApCollectionService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.common.constants.message.UpdateArticleMess;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        //条件判断
        if(dto == null || dto.getEntryId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询
        Double score = cacheService.zScore("BEHAVIOR:COLLECTION:" + user.getId(), dto.getEntryId() + ":" + dto.getType());
        if (score != null && dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
        }

        //收藏
        if(dto.getOperation() == 0){
            log.info("文章收藏，保存key:{},{},{}", dto.getEntryId(), user.getId().toString(), JSON.toJSONString(dto));
            dto.setPublishedTime(new Date());
            cacheService.zAdd("BEHAVIOR:COLLECTION:" + user.getId(), dto.getEntryId() + ":" + dto.getType(), System.currentTimeMillis());


            //**********实时计算消息****文章id + 行为******************

            UpdateArticleMess mess =
                    new UpdateArticleMess(UpdateArticleMess.UpdateArticleType.COLLECTION, dto.getEntryId());
            kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, JSON.toJSONString(mess));
            log.info("COLLECTION:{}", mess);

            //******************************************


        }else {
            //取消收藏
            log.info("文章收藏，删除key:{},{},{}",dto.getEntryId(),user.getId().toString(), JSON.toJSONString(dto));
            cacheService.zRemove("BEHAVIOR:COLLECTION:"+user.getId(),
                    dto.getEntryId()+":"+dto.getType());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
